package com.testdemo.common.base;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.CallSuper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.lzy.okgo.OkGo;
import com.testdemo.MyApplication;
import com.testdemo.common.utils.LogUtil;
import com.testdemo.common.utils.ToastUtil;
import com.testdemo.common.view.SimpleDialog;

import java.util.ArrayList;

import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;

/**
 * Created by dell on 2017/11/20.
 */

public abstract class BaseFragment extends Fragment {

    public Context mContext;
    public BaseActivity mActivity;
    boolean isShowingProgressDialog = false;
    public LoadingDialog dialog;
    public View rootView;

    public boolean onCreate = false;


    public abstract int getLayoutResourceId();
    public abstract void init();

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (BaseActivity) getActivity();
        mContext = mActivity.getApplicationContext();
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        onCreate = true;
        if (firstVisible){
            onFirstVisibleInViewPager();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden  && !firstVisible){
            firstVisible = true;
            onFirstVisibleInViewPager();
        }
    }

    public void onEventMainThread(Object event) {

    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        OkGo.getInstance().cancelTag(this);
        super.onDestroy();
    }

    public boolean firstVisible = false;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && !firstVisible) {
            firstVisible = true;
            if (onCreate){
                onFirstVisibleInViewPager();
            }
        }
    }


    /**
     * 在ViewPager（第一次显示）懒加载时用的，直接在Activity中的，不会触发此方法，Activity中请在init()中加载数据
     */
    public void onFirstVisibleInViewPager(){
    }



    @Override
    @CallSuper
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        LogUtil.e("UiClassName:",getClass().getSimpleName());
        LogUtil.e("UiClassName:",rootView+"-----getLayoutResourceId="+getLayoutResourceId());
        EventBus.getDefault().register(this);
        if (rootView == null) {
            rootView = inflater.inflate(getLayoutResourceId(), container, false);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        ButterKnife.bind(this,rootView);
        init();
        return rootView;
    }

    /**
     * 显示弹窗
     */
    public void showProgressDialog(){showProgressDialog(true);}
    public void showProgressDialog(boolean cancelable) {
        try {
            if (dialog == null) {
                dialog = new LoadingDialog(mActivity,mActivity.mFragmentManager);
                dialog.setCancelable(cancelable);
                if (!mActivity.isFinishing() && !isShowingProgressDialog) {
                    isShowingProgressDialog = true;
                    dialog.show();
                }
                dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        isShowingProgressDialog = false;
                        dialog.cancel();
                        onProgressDialogCancelByUser();
                    }
                });
            } else if (!isShowingProgressDialog && !mActivity.isFinishing()) {
                if (!dialog.isAdded()) {
                    isShowingProgressDialog = true;
                    dialog.show();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 隐藏弹窗
     */
    public void dismissProgressDialog() {
        try {
            if (dialog != null && isShowingProgressDialog) {
                isShowingProgressDialog = false;
                dialog.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 当用户按返回键取消了等待框
     */
    public void onProgressDialogCancelByUser(){
        OkGo.getInstance().cancelTag(this);
    }

    public void start(Class<? extends Activity> activityClass) {
        Intent intent = new Intent();
        intent.setClass(MyApplication.getInstance(), activityClass);
        this.startActivity(intent);
    }

    public void start(Class<? extends Activity> activityClass, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(MyApplication.getInstance(), activityClass);
        this.startActivityForResult(intent, requestCode);
    }

    public void start(Intent i, int requestCode) {
        this.startActivityForResult(i, requestCode);
    }

    public void start(Class<? extends Activity> activityClass, BaseIntent baseIntent) {
        Intent intent = new Intent();
        intent.setClass(MyApplication.getInstance(), activityClass);
        baseIntent.setIntent(intent);
        this.startActivity(intent);
    }

    public void start(Class<? extends Activity> activityClass, BaseIntent baseIntent, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(MyApplication.getInstance(), activityClass);
        baseIntent.setIntent(intent);
        this.startActivityForResult(intent, requestCode);
    }

    public interface BaseIntent {
        void setIntent(Intent intent);
    }


    /**
     * 动态权限的获取被允许了
     */
    public void onPermissionsGot(int requestCode) {

    }

    /**
     * 动态权限的获取被取消了
     */
    public void onPermissionsCancel(int requestCode) {
        ToastUtil.showText("您拒绝了授予权限");


    }

    public static int ACTION_GET_PERMISSION = 15894;

    public void getPermissions(int requestCode, @NonNull String... permissions) {
        ArrayList<String> requestPermissions = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(MyApplication.myApplication, permission) == PackageManager.PERMISSION_DENIED) {//没有权限
                requestPermissions.add(permission);
            }
        }
        if (requestPermissions.isEmpty()) {
            onPermissionsGot(requestCode);
        } else {
            String[] strings = new String[requestPermissions.size()];
            for (int i = 0; i < requestPermissions.size(); i++) {
                strings[i] = requestPermissions.get(i);
            }
            requestPermissions(strings, ACTION_GET_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == ACTION_GET_PERMISSION) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != 0) {//没有被允许
                    //检测到有拒绝时打勾了的情况，直接弹框去设置页面让用户设置
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(mActivity, permissions[i])) {
                        new SimpleDialog(mActivity)
                                .setTitleText("前往设置页面授予权限")
                                .setConfirmButtonText("确定")
                                .setCancelButtonText("取消")
                                .setOnConfirmListener(new SimpleDialog.OnConfirmListener() {
                                    @Override
                                    public void onConfirm(DialogInterface dialog) {
                                        dialog.dismiss();
                                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                        intent.setData(Uri.parse("package:" + mContext.getPackageName())); // 根据包名打开对应的设置界面
                                        startActivity(intent);
                                    }
                                }).show();
                        return;
                    }
                    onPermissionsCancel(requestCode);
                    return;
                }
            }
            onPermissionsGot(requestCode);
        }
    }
}
